package com.sky.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Set;

@Component
@Slf4j
@Aspect
public class AutoClearRedisAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Before("@annotation(com.sky.annotation.AutoClearAllClientDishRedis)")
    public void autoClearAllClientDishRedis(JoinPoint joinPoint) {
        log.info("开始自动清理缓存");
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    @Before("@annotation(com.sky.annotation.AutoClearClientOneDishRedis)")
    public void autoClearOneClientDishRedis(JoinPoint joinPoint) throws Exception {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Object[] args = joinPoint.getArgs();
        Object entity = args[0];
        Method categoryId = entity.getClass().getDeclaredMethod("getCategoryId");
        String key = "dish_" + categoryId.invoke(entity);
        redisTemplate.delete(key);
    }

}
